#include "PCF8563.h"

PCF8563 pcf;

void PCF8563::begin()
{
    Wire.begin(SDA_PIN,SCL_PIN);
    Wire.setClockStretchLimit(3000000);
    Wire.setClock(400000); 
}

void PCF8563::init()
{
    Wire.beginTransmission(slave);
	Wire.write(0x00);
    Wire.write(0x00);
    Wire.write(0x00);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x01);
    Wire.write(0x80);
    Wire.write(0x80);
    Wire.write(0x80); 
    Wire.write(0x80);
    Wire.write(0x00);
    Wire.write(0x00);
    Wire.write(0x00);
    Wire.endTransmission();
}


void PCF8563::write_time(u8 hour,u8 min,u8 second)
{
    Wire.beginTransmission(slave);
    Wire.write(second_slave);
    Wire.write(num_to_bcd(second));
    Wire.write(num_to_bcd(min));
    Wire.write(num_to_bcd(hour));
    Wire.endTransmission();
}

void PCF8563::write_day(u8 year,u8 month,u8 day,u8 week)
{
    Wire.beginTransmission(slave);
    Wire.write(day_slave);
    Wire.write(num_to_bcd(day));
    Wire.write(num_to_bcd(week));
    Wire.write(num_to_bcd(month)|0x80);
    Wire.write(num_to_bcd(year));
    Wire.endTransmission();

}
void PCF8563::read_time()
{
    Wire.beginTransmission(slave);
    Wire.write(second_slave);
    Wire.endTransmission();
    Wire.requestFrom(slave, 3); //request 3 bytes
    second=bcd_to_num(Wire.read()&0x7f);
    min=bcd_to_num(Wire.read()&0x7f);
    hour=bcd_to_num(Wire.read()&0x3f);
}

void PCF8563::read_day()
{
    Wire.beginTransmission(slave);
    Wire.write(day_slave);
    Wire.endTransmission();
    Wire.requestFrom(slave, 4); //request 3 bytes
    day=bcd_to_num(Wire.read()&0x3f);
    week=bcd_to_num(Wire.read()&0x07);
    month=bcd_to_num(Wire.read()&0x1f);
    year=bcd_to_num(Wire.read());
}

u8 PCF8563::num_to_bcd(u8 dat)
{
    return ( (dat/10*16) + (dat%10) );
}

u8 PCF8563::bcd_to_num(u8 dat)
{
    return ( (dat/16*10) + (dat%16) );
}
